package com.yan.key;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.yan.key.overlayutil.PoiOverlay;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    MapView mMapView;
    BaiduMap mBaiduMap;

    //百度地图定位相关的类
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    //第一次定位
    private boolean isFirstLocation;

    //检索
    PoiSearch mPoiSearch;

    //在线建议检索
    SuggestionSearch mSuggestionSearch;

    //自动成功textview
    AutoCompleteTextView actv;

    //城市输入
    EditText et_city;

    Button btn;
    Button btnNext;

    //当前的下标
    private int currentIndex;

    //每页的容量
    private static final int PAGECAPACITY = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        mContext = this;
        //设置该地图为普通地图模式
        mBaiduMap = mMapView.getMap();
        //普通地图
//        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        //初始化定位参数
        initLocation();
        //开始定位
        mLocationClient.start();
        initSearch();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mPoiSearch.destroy();
        mSuggestionSearch.destroy();
        actv.removeTextChangedListener(mTextWatcher);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {//定位成功了
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());

            if (location.getCity() != null) {
                et_city.setText(location.getCity());
            }
            setMarker(location);
            if (!isFirstLocation) {
                setUserMapCenter(location);
                isFirstLocation = true;
            }

        }
    }


    /**
     * 设置百度地图定位的参数
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;//30s定位一次
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    Marker mMarker;
    Overlay mMarkerText;

    /**
     * 添加marker
     */
    private void setMarker(BDLocation location) {
//        Log.v("pcw","setMarker : lat : "+ lat+" lon : " + lon);
        //如果有定义的Maker坐标点 就移除旧的
        if (mMarker != null) {
            mMarker.remove();
        }
        if (mMarkerText != null) {
            mMarker.remove();
        }
        //定义文字所显示的坐标点

        LatLng point = new LatLng(location.getLatitude(), location.getLongitude());

//构建文字Option对象，用于在地图上添加文字
        OverlayOptions textOption = new TextOptions()
                .bgColor(0xAAFFFF00)
                .fontSize(18)
                .fontColor(0xFF0000FF)
                .text("当前位置")
                .rotate(0)
                .position(point);
//在地图上添加该文字对象并显示
        mMarkerText = mBaiduMap.addOverlay(textOption);

        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.location);

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示移除之前的视图？？
        mMarker = (Marker) mBaiduMap.addOverlay(option);
    }

    /**
     * 设置中心点
     */
    private void setUserMapCenter(BDLocation location) {
        LatLng cenpt = new LatLng(location.getLatitude(), location.getLongitude());
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .zoom(18)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);

    }


    private List<PoiInfo> mPoiInfoList;

    private ArrayAdapter<String> aAdapter;

    List<String> listString;

    private void initSearch() {

        actv = (AutoCompleteTextView) findViewById(R.id.actv);

        et_city = (EditText) findViewById(R.id.et_city);

        btn = (Button) findViewById(R.id.btn);
        btnNext = (Button) findViewById(R.id.btn_next);

        mPoiInfoList = new ArrayList<>();
        listString = new ArrayList<>();

        //在线建议检索
        mSuggestionSearch = SuggestionSearch.newInstance();
        //poi检索
        mPoiSearch = PoiSearch.newInstance();

        actv.addTextChangedListener(mTextWatcher);

        mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
        actv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                actv.setText(listString.get(i));
                actv.setSelection(listString.get(i).length());
            }
        });


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentIndex = 0;
                startSearch();
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentIndex++;
                startSearch();
            }
        });


        mSuggestionSearch.setOnGetSuggestionResultListener(new OnGetSuggestionResultListener() {
            @Override
            public void onGetSuggestionResult(SuggestionResult suggestionResult) {
                if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
                    return;
                    //未找到相关结果
                }
                List<SuggestionResult.SuggestionInfo> list = suggestionResult.getAllSuggestions();

                listString.clear();
                for (SuggestionResult.SuggestionInfo suggestionInfo : list) {
                    Log.i("suggestionInfo", "suggestionInfo====>" + suggestionInfo.toString());
                    if (suggestionInfo.key != null) {
                        listString.add(suggestionInfo.key);
                    }
                }
                aAdapter = new ArrayAdapter<>(
                        mContext,
                        R.layout.support_simple_spinner_dropdown_item, listString);
                actv.setAdapter(aAdapter);
                aAdapter.notifyDataSetChanged();
            }
        });

    }

    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {

        @Override
        public void onGetPoiResult(PoiResult poiResult) {
            if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                Toast.makeText(mContext, "抱歉，未找到结果",
                        Toast.LENGTH_LONG).show();
                System.out.println("抱歉，未找到结果");
                return;
            }
            if (poiResult.error != SearchResult.ERRORNO.NO_ERROR) {
                Toast.makeText(mContext, "抱歉，搜索出错了",
                        Toast.LENGTH_LONG).show();
                System.out.println("抱歉，搜索出错了");
                return;
            }

            List<PoiInfo> list = poiResult.getAllPoi();

            mPoiInfoList.clear();
            mPoiInfoList = poiResult.getAllPoi();
            for (PoiInfo poiInfo : list) {
                Log.i("PoiAddrInfo", "btn====> poiInfo.name" + poiInfo.name + "  poiInfo.address" + poiInfo.address);
                //   将结果显示到地图上
                mBaiduMap.clear();


                //创建PoiOverlay
                PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
                //设置overlay可以处理标注点击事件
                mBaiduMap.setOnMarkerClickListener(overlay);
                //设置PoiOverlay数据
                overlay.setData(poiResult);
                //添加PoiOverlay到地图中
                overlay.addToMap();
                overlay.zoomToSpan();

            }
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };

    private Context mContext;

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (et_city.getText().toString() == null) {
                Log.i("et_city", "没有输入城市");
                return;
            }
            if (actv.getText().toString() == null) {
                Log.i("et_city", "没有输入具体地址");
                return;
            }
            mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                    .city(et_city.getText().toString())
                    .keyword(actv.getText().toString()));
        }
    };

    /**
     * btn 点击开始搜索
     */
    private void startSearch() {
        if (et_city.getText().toString() == null) {
            Log.i("et_city", "没有输入城市");
            return;
        }
        if (actv.getText().toString() == null) {
            Log.i("actv", "没有输入具体地址");
            return;
        }

        //点击后的搜索结果要直接显示
        Log.i("et_city", et_city.getText().toString() + "actv" + actv.getText().toString());
        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(et_city.getText().toString())
                .keyword(actv.getText().toString())
                .pageCapacity(PAGECAPACITY)
                .pageNum(currentIndex));
    }

    class MyPoiOverlay extends PoiOverlay {
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            showMessageOKCancel("您选择的地点为：" + mPoiInfoList.get(index).name + "\n" + mPoiInfoList.get(index).address, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(mContext, "选择成功",
                            Toast.LENGTH_LONG).show();
                }
            });

            //得到坐标了
            return true;
        }
    }

    public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(mContext)
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

}


